from models.notice import Notice
from utils.decorators.cache import cache
from . import api
from flask import request


@api.route('/notices', methods=['GET'])
@cache(set(), 120)
def handle_notice():
    stick_notices = Notice.query.filter(Notice.is_stick == 1, Notice.is_show == 1).order_by(Notice.id_.desc()).all()
    not_stick_notices = Notice.query.filter(Notice.is_stick == 0, Notice.is_show == 1).order_by(Notice.id_.desc()).all()
    return {
        'code': 0,
        'data': {
            'stick': [x.serialize_without_content() for x in stick_notices],
            'notStick': [x.serialize_without_content() for x in not_stick_notices]
        }
    }


@api.route('/notices/<int:notice_id>', methods=['GET'])
@cache(set(), 120)
def handle_notice_detail(notice_id: int):
    return {
        'code': 0,
        'data': Notice.query.get(notice_id).serialize()
    }


@api.route('/notices/latest', methods=['GET'])
@cache(set(), 1800)
def handle_notice_latest():
    latest_notice = Notice.query.filter(Notice.is_important == 1, Notice.is_show == 1).order_by(Notice.time.desc()).first()
    return {
        'code': 0,
        'data': latest_notice.serialize()if latest_notice else []
    }


@api.route('/notices/pop', methods=['GET'])
@cache({'type'}, 30)
def handle_notice_pop():
    pop_type = request.args.get('type', 1)
    if pop_type == "home":
        pop_type = 1
    elif pop_type == "agent":
        pop_type = 2
    pop_notices = Notice.query.filter(Notice.is_pop == pop_type).first()
    return {
        'code': 0,
        'data': pop_notices.serialize_pop()if pop_notices else []
    }
